import React ,{ Component }  from 'react'

import {Table as AntTable,Menu, Dropdown,Icon,Button,Select,Radio,Anchor,Pagination} from 'antd'

import {Link as Linko} from 'react-router-dom'


import QRCode from 'qrcode.react'

import { connect } from 'react-redux'

import {detail} from '../actions/module'

import './table.css'

import { Redirect } from 'react-router-dom'; 

import createHistory from 'history/createHashHistory';
import {timestampToTime} from "../util/util";


const { Link } = Anchor;

const history = createHistory();




const styles=['neutral','positive','reverse']

const Option = Select.Option;

//已阅未阅
class Readtag extends Component{
  constructor(props){
    super(props);
    if(!localStorage.readingList){
      localStorage.readingList=JSON.stringify(["0"])
    }
    let Hlist=JSON.parse(localStorage.readingList)
    let isHas=Hlist.indexOf(this.props.tagId)>=0
    this.state={
      collection:isHas,
    }
  }
  handleClick(value){
    if(!this.state.collection){
      let list=JSON.parse(localStorage.readingList)
      list.push(this.props.tagId)
      localStorage.readingList=JSON.stringify(list)
      }
    this.setState(prevState=>({
      collection:!prevState.collection
    }))
  }
  render(){
    if(!localStorage.readingList){
      localStorage.readingList=JSON.stringify(["0"])
    }
    let Hlist=JSON.parse(localStorage.readingList)
    let isHas=Hlist.indexOf(this.props.tagId)>=0
      return(
        <span className={isHas ? "opti hasread":'opti noread'} onClick={()=>this.handleClick(isHas?this.props.title[0]:this.props.title[1])}>
          <Icon type={isHas?this.props.icon[0]:this.props.icon[1]} />{isHas?this.props.title[0]:this.props.title[1]}</span>     
      )
  }
}
class Etag extends Component{
  constructor(props){
    super(props);
    this.state={
      publish:this.props.publish
    }
  }
  handleClick(id,tit,content) {
    this.setState(prevState=>({
      publish:!prevState.publish
    }))
    this.props.onCtrClick(id)
  }
  componentWillReceiveProps(nextProps){
    this.setState({
      publish:nextProps.publish
    })
  }
  render(){
    if(!this.state.publish){
      return <span  className="opti" onClick={()=>this.handleClick(this.props.id,this.props.tit,this.props.content)}><Icon type="upload"></Icon>{this.state.publish?'已上报':'上报'}</span>
    }else{
      return <span  className="opti"><Icon type="upload"></Icon>{this.state.publish?'已上报':'上报'}</span>
    }
   
  }
}  
class Tagmark extends Component{
  constructor(props){
    super(props);
    this.state={
    }
  }
  handleClick(e){
    this.props.chageId(this.props.ID)
  }
  render(){
    return(
        <label className="check-label">
          <input type="radio" name="mark" onChange={(e)=>this.handleClick(e)}/>
          <span className="opti">
          <Icon type="tags" />书签</span> 
        </label>
    )
  }
}

class Tag extends Component{
  constructor(props){
    super(props);
    this.state={
      collection:this.props.collection==='true'?true:false
    }
  }
  handleClick(value){
    this.setState(prevState=>({
      collection:!prevState.collection
    }))
    this.props.onCtrClick(value)
  }
  render(){
    return(
      <span className="opti" onClick={()=>this.handleClick(this.state.collection?this.props.title[0]:this.props.title[1])}><Icon type={this.state.collection?this.props.icon[0]:this.props.icon[1]} />{this.state.collection?this.props.title[0]:this.props.title[1]}</span>
    )
  }
}

const Btn = (props)=>({
  render(){
    return(
      <span className="opti" onClick={()=>{this.props.onCtrClick(this.props.id)}}><Icon type={this.props.icon}></Icon>{this.props.title}</span>
    )
  }
})

class OverlayVisible  extends Component{
  constructor(props){
    super(props);
    this.state = {
      visible: false,
      value:''
    };
  }

  handleMenuClick = (e) => {
    this.setState({
      value:this.props.oValue
    })
    
  }
  handleVisibleChange = (flag) => {
    this.setState({ visible: flag });
  }

    fn_render=(flag,b)=>{
    if(flag){
      return <QRCode value={b} />
    }
    else{
      return 
    }
  }
  handhover(){
    this.setState({ visible: false });
  }
  render(){
    const menu= (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="1">微信</Menu.Item>
        <Menu.Item key="2">微博</Menu.Item>
      </Menu>
  )

  return(
    <div className="share-pos" >
      <Dropdown overlay={menu} onVisibleChange={this.handleVisibleChange} visible={this.state.visible}>
      <span className="ant-dropdown-link">
      <Icon type="share" />分享
      </span>
    </Dropdown>
    <div className={this.state.visible?'post show':'post hide'} onMouseOver={()=>this.handhover()}>
      {this.fn_render(true,this.state.value)}
    </div>
  </div>
  )
  }

}

@connect(
  state => state.moduleInforesult,
  {detail}
)

export default class Table extends Component{
  constructor(props){
    super(props);
    this.mountProps(props);
    this.state={
      id:'#'
    }
    this.handleChange=this.handleChange.bind(this)
  }

  // componentWillReceiveProps(props) {
  //   this.mountProps(props);
  // }

  fnPensity(value){
    var typrht=''
    switch(parseInt(value)){
      case -1:
      return typrht='全部'
      case 0:
      return typrht='中性'
      case 1:
      return typrht='正面'
      case 2:
      return typrht='负面'
      default:
      return typrht=value
    }
    return typrht
  }
  changeId(Id){
      this.setState({
        id:'#'+Id
      })
  }
  //链接跳转id设置
  detailset(id,key){
    if(!localStorage.id){
      localStorage.id=id;
      localStorage.titleContentPrint=key;
    }else{
      localStorage.id=id;
      localStorage.titleContentPrint=key
    }
    //this.props.detail(id,key)
    //return <Redirect push to="/detail" />;
    

  }
createMarkup(page) { 
  // this.keyLight(page,'再谈')
  let res = page.replace(/<br \/>/g,'').replace(/<br\/>/g, '').replace(/{{{/g,"<span class='light' style='color:red'>").replace(/}}}/g,"</span>")
  return {__html: res}; 
  };

  mountProps(props) {
    const {
      header,
      action,
      headerWidth,
      currentPage,
      data,
      } = props;
    this.state = {
      currentPage,

    }
    this.makeColumns(header, action, headerWidth, data);
  }
  makeColumns(headers, action, headerWidth, data){
    this.columns = [{
      dataIndex: 'name',
      key: 'name',
      render:(text,record)=>(
        <div className="srcpos">
          {/* <img className="src1" src={record.domain===' '?'image/defult':'image/'+record.domain +'.png'}  alt=""></img> */}
          <img className="src1" src={'image/'+record.domain+'.png'}  alt=""></img>
          <img className="src2" src={'image/defult.png'}  alt=""></img>
        </div>
      ),
    },{
      dataIndex: 'address',
      key: 'address',
      render:(text,record)=>(
        <div className="fiter-info" id={record.id}>
          <div className="title-p">
            <Linko to={'/detail?t='+Date.parse(new Date())+'&type='+(record.favoriteId?1:0)} target='_blank'>
              <div  className='titl' onClick={()=>this.detailset(record.id,record.titleContentPrint)}
                    dangerouslySetInnerHTML={this.createMarkup(record.title.replace(/<br\/>/g, '').replace(/{{{/g,"<span class='light' style='color:red'>").replace(/}}}/g,"</span>"))}></div>
              </Linko>
            <div className={"type " + styles[record.positiveOrNegative]} style={{marginRight:'30px'}}>{this.fnPensity(record.positiveOrNegative)}</div>
            <div style={{position:'absolute',right:0}}>{timestampToTime(record.addTime)}</div>
          </div>
          <div className='info show'  dangerouslySetInnerHTML={this.createMarkup(record.content)}></div>
          <div className="footer">
            <div className="source">
              <span>来源：</span>
              <span>{record.webSite}</span>
            </div>
    
            <div className="share">
              <OverlayVisible oValue={record.url}></OverlayVisible>
              {/* <Tag icon={["upload","upload"]} title={['上报','已上报']}  onCtrClick={this.props.click}></Tag> */}
              <Etag id={record.id} onCtrClick={this.props.pExoort} publish={record.publish} tit={record.title} content={record.content}></Etag>
              <Tag icon={['star','star-o']} title={['已收藏','收藏']} onCtrClick={this.props.click} id={record.id} tit={record.title} content={record.content} poTime={record.poTime}
              webSite={record.webSite} domain={record.domain} positiveOrNegative={record.positiveOrNegative} collection={record.collected}></Tag>
              <Readtag icon={['eye-o','eye']} title={['取消已阅','标记已阅']} tagId={record.id} ishas={this.props.ishas}></Readtag>
              <Tagmark ID={record.id} chageId={(value)=>this.changeId(value)}></Tagmark>
              <Btn icon={'delete'} onCtrClick={this.props.delete} title='删除' id={record.id}></Btn>
            </div>
          </div>
        </div>
      )
    }];  
      }

  onPageChangeHandler = (currentPage) => {
    // this.setState({
    //   currentPage,
    // });
    this.props.onChange(currentPage)
    // if ('onChange' in this.props) {
     
    //   this.props.onChange(currentPage);
    // }
  }
  handleChange(value){
    this.props.changeSize(Number(value))
  }
  render(){
    return(
      <div>
        <div className="t">
          <Button onClick={this.props.deleteData}>删除</Button>
          <Button onClick={this.props.exportSeles}>导出</Button>
          <Button onClick={this.props.tagRead}>标记为已阅</Button>
          <Anchor >
            <Link href={this.state.id} title="返回书签" showInkInFixed={false} affix={false}></Link>
          </Anchor>
          <Button>批量上报</Button>
          <Select style={{width: 200}} onChange={this.handleChange} defaultValue={'10条/页'}>
            <Option value="10">10条/页</Option>
            <Option value="5">5条/页</Option>
            <Option value="50">50条/页</Option>
          </Select>
        </div>
        <AntTable
            rowKey="id"
            rowSelection={this.props.rowSelection}
            columns={this.columns}  
            dataSource={this.props.data}
            loading={this.props.loading}
            pagination={this.props.pagination !== false ? {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.currentIndeX,
            onChange: this.onPageChangeHandler,
            Abstract:this.props.Abstract,
            showTotal(total, range) {
              return <span className={'pageTotal'}>共<span className={'count'}>{total}</span>条</span>;
            },
          } : false}></AntTable>
      </div>
    )
  }
}